package com.qunar.toku.handler;

import java.lang.reflect.Method;

import org.jboss.netty.channel.Channel;

import com.qunar.toku.proxy.Provider;
import com.qunar.toku.proxy.RequestProtocol;

public final class ServerHandler extends ChannelServerHandler {

	@Override
	protected void execute(Channel channel, Object message) {
		
		RequestProtocol protocol = (RequestProtocol) message;
		Object obj = protocol.getClazz();
		Object[] params = (Object[]) protocol.getMessage();
		Object ret = null;

		try {
			Method method = null;
			String methodName = protocol.getMethod();

			Method[] methods = obj.getClass().getDeclaredMethods();
			for (Method m : methods) {
				if (m.getName().equals(methodName)) {
					method = m;
					break;
				}
			}

			ret = method.invoke(obj, params);
			Provider provider = new Provider(channel, protocol);
			provider.send(ret);
		} catch (Exception e) {
			throw new IllegalAccessError(e.getMessage());
		}

	}
}
